<script setup lang="ts">
import { ref, watch, onMounted, onActivated, onDeactivated, onBeforeUnmount } from 'vue';
import TrafficLight from '@/components/devices/TrafficLight.vue';
import type { ProjectInfo } from './types';
import type { Part } from '@/types/Part';
import { Project } from '@/components/projects/Project';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getPartsAsync } from '@/utils/project-api';
import { useDeviceMaintenanceSignalRClientStore } from '@/stores/signalr-client';

const currentProjectId = ref<string>('');
const projectOption = ref<ProjectInfo[]>([]);
const currentPartId = ref<string>('');
const partsOption = ref<Part[]>([]);
const showTable = ref<boolean>(false);
const subcompoent = ref<Part[]>([]);

const anodeMixerRegex = /^[0-9]{1,3}#阴极制浆机-[\w]{1,}$/;
const project = new Project();
const route = useRoute();
const clientStore = useDeviceMaintenanceSignalRClientStore();

if (!clientStore.isConnected()) {
  clientStore.connectServerAsync();
}

// 监听路由项目ID参数变化
watch(
  () => route.query.projectId,
  (newParam) => {
    if (typeof newParam === 'string') {
      projectChange(newParam);
    }
  }
);
// 监听路由部件Id变化
watch(
  () => route.query.partId,
  (newParam) => {
    if (typeof newParam === 'string') {
      partChange(newParam);
    }
  }
);

onMounted(() => {
  init();
  const { projectId, partId } = route.query;
  if (projectId && typeof projectId === 'string')
    projectChange(projectId).then(() => {
      if (partId && typeof partId === 'string') partChange(partId);
    });
});
// 初始化请求接口
const init = async () => {
  try {
    const resp = await project.getAsync(0, 1000);
    projectOption.value = resp;
  } catch (error) {
    if (error) return ElMessage.error(error || '获取项目列表错误！');
  }
};

// 订阅各个部件 id
async function subscribePartsAsync() {
  const tempHighSpeedMotor = subcompoent.value.find((item) =>
    item.partName.endsWith('高速分散腔电机-传动带')
  );
  if (tempHighSpeedMotor != null) {
    highSpeedMotor.value.partId = tempHighSpeedMotor.id;
    await clientStore.subscribeAsync(highSpeedMotor.value.partId, (result) => {
      // 当前转速
      if (result.taskName == highSpeedMotor.value.currentSpeed.key) {
        highSpeedMotor.value.currentSpeed.value = result.value;
      }
      // 当前寿命
      else if (result.taskName == highSpeedMotor.value.currentValue.key) {
        highSpeedMotor.value.currentValue.value = result.value;
      }
      // 预警寿命
      else if (result.taskName == highSpeedMotor.value.warningValue.key) {
        highSpeedMotor.value.warningValue.value = result.value;
      }
      // 停机寿命
      else if (result.taskName == highSpeedMotor.value.stopValue.key) {
        highSpeedMotor.value.stopValue.value = result.value;
      }
    });
  }

  const tempCirculatingTankBeltA = subcompoent.value.find((item) =>
    item.partName.endsWith('循环罐A')
  );
  if (tempCirculatingTankBeltA != null) {
    circulatingTankBeltA.value.partId = tempCirculatingTankBeltA.id;
    await clientStore.subscribeAsync(circulatingTankBeltA.value.partId, (result) => {
      // 当前压强
      if (result.taskName == circulatingTankBeltA.value.pressure.key) {
        circulatingTankBeltA.value.pressure.value = result.value;
      }
      // 当前搅拌速度
      else if (result.taskName == circulatingTankBeltA.value.mixingSpeed.key) {
        circulatingTankBeltA.value.mixingSpeed.value = result.value;
      }
      // 当前分散速度
      else if (result.taskName == circulatingTankBeltA.value.distributeSpeed.key) {
        circulatingTankBeltA.value.distributeSpeed.value = result.value;
      }
      // 当前寿命
      else if (result.taskName == circulatingTankBeltA.value.currentValue.key) {
        circulatingTankBeltA.value.currentValue.value = result.value;
      }
      // 预警寿命
      else if (result.taskName == circulatingTankBeltA.value.warningValue.key) {
        circulatingTankBeltA.value.warningValue.value = result.value;
      }
      // 停机寿命
      else if (result.taskName == circulatingTankBeltA.value.stopValue.key) {
        circulatingTankBeltA.value.stopValue.value = result.value;
      }
    });
  }

  const tempCirculatingTankBeltB = subcompoent.value.find((item) =>
    item.partName.endsWith('循环罐B')
  );
  if (tempCirculatingTankBeltB != null) {
    circulatingTankBeltB.value.partId = tempCirculatingTankBeltB.id;
    await clientStore.subscribeAsync(circulatingTankBeltB.value.partId, (result) => {
      // 当前压强
      if (result.taskName == circulatingTankBeltB.value.pressure.key) {
        circulatingTankBeltB.value.pressure.value = result.value;
      }
      // 当前搅拌速度
      else if (result.taskName == circulatingTankBeltB.value.mixingSpeed.key) {
        circulatingTankBeltB.value.mixingSpeed.value = result.value;
      }
      // 当前分散速度
      else if (result.taskName == circulatingTankBeltB.value.distributeSpeed.key) {
        circulatingTankBeltB.value.distributeSpeed.value = result.value;
      }
      // 当前寿命
      else if (result.taskName == circulatingTankBeltB.value.currentValue.key) {
        circulatingTankBeltB.value.currentValue.value = result.value;
      }
      // 预警寿命
      else if (result.taskName == circulatingTankBeltB.value.warningValue.key) {
        circulatingTankBeltB.value.warningValue.value = result.value;
      }
      // 停机寿命
      else if (result.taskName == circulatingTankBeltB.value.stopValue.key) {
        circulatingTankBeltB.value.stopValue.value = result.value;
      }
    });
  }

  const tempTransferTank = subcompoent.value.find((item) => item.partName.endsWith('中转罐'));
  if (tempTransferTank != null) {
    transferTank.value.partId = tempTransferTank.id;
    await clientStore.subscribeAsync(transferTank.value.partId, (result) => {
      // 当前速度
      if (result.taskName == transferTank.value.currentSpeed.key) {
        transferTank.value.currentSpeed.value = result.value;
      }
      // 当前寿命
      else if (result.taskName == transferTank.value.currentValue.key) {
        transferTank.value.currentValue.value = result.value;
      }
      // 预警寿命
      else if (result.taskName == transferTank.value.warningValue.key) {
        transferTank.value.warningValue.value = result.value;
      }
      // 停机寿命
      else if (result.taskName == transferTank.value.stopValue.key) {
        transferTank.value.stopValue.value = result.value;
      }
    });
  }
}

async function unsubscribeAsync() {
  if (highSpeedMotor.value.partId != '') {
    await clientStore.unsubscribeAsync(highSpeedMotor.value.partId);
  }
  if (circulatingTankBeltA.value.partId != '') {
    await clientStore.unsubscribeAsync(circulatingTankBeltA.value.partId);
  }
  if (circulatingTankBeltB.value.partId != '') {
    await clientStore.unsubscribeAsync(circulatingTankBeltB.value.partId);
  }
  if (transferTank.value.partId != '') {
    await clientStore.unsubscribeAsync(transferTank.value.partId);
  }
}

onActivated(async () => {
  await subscribePartsAsync();
});

// 在从 DOM 上移除、进入缓存
// 以及组件卸载时调用
onDeactivated(async () => {
  await unsubscribeAsync();
});

onBeforeUnmount(async () => {
  await unsubscribeAsync();
});

// 高速分散腔电机-传动带
const highSpeedMotor = ref({
  partId: '',
  status: 'yellow',
  // 当前电机转速
  currentSpeed: {
    key: '当前转速',
    lable: '当前转速',
    value: '--'
  },
  currentValue: {
    key: '保养运行值',
    lable: '当前寿命',
    value: '--'
  },
  warningValue: {
    key: '保养预警值',
    lable: '预警寿命',
    value: '--'
  },
  stopValue: {
    key: '保养停机值',
    lable: '停机寿命',
    value: '--'
  }
});

// 循环罐A
const circulatingTankBeltA = ref({
  partId: '',
  status: 'yellow',
  // 当前压强
  pressure: {
    key: '当前压强',
    lable: '当前压强',
    value: '--'
  },
  // 搅拌速度
  mixingSpeed: {
    key: '当前搅拌速度',
    lable: '当前搅拌速度',
    value: '--'
  },
  // 分散速度
  distributeSpeed: {
    key: '当前分散速度',
    lable: '当前分散速度',
    value: '--'
  },
  currentValue: {
    key: '保养运行值',
    lable: '当前寿命',
    value: '--'
  },
  warningValue: {
    key: '保养预警值',
    lable: '预警寿命',
    value: '--'
  },
  stopValue: {
    key: '保养停机值',
    lable: '停机寿命',
    value: '--'
  }
});

// 循环罐B
const circulatingTankBeltB = ref({
  partId: '',
  status: 'yellow',
  // 当前压强
  pressure: {
    key: '当前压强',
    lable: '当前压强',
    value: '--'
  },
  // 搅拌速度
  mixingSpeed: {
    key: '当前搅拌速度',
    lable: '当前搅拌速度',
    value: '--'
  },
  // 分散速度
  distributeSpeed: {
    key: '当前分散速度',
    lable: '当前分散速度',
    value: '--'
  },
  currentValue: {
    key: '保养运行值',
    lable: '当前寿命',
    value: '--'
  },
  warningValue: {
    key: '保养预警值',
    lable: '预警寿命',
    value: '--'
  },
  stopValue: {
    key: '保养停机值',
    lable: '停机寿命',
    value: '--'
  }
});

// 中转罐
const transferTank = ref({
  partId: '',
  status: 'yellow',
  // 当前速度
  currentSpeed: {
    key: '当前速度',
    lable: '当前速度',
    value: '--'
  },
  currentValue: {
    key: '保养运行值',
    lable: '当前寿命',
    value: '--'
  },
  warningValue: {
    key: '保养预警值',
    lable: '预警寿命',
    value: '--'
  },
  stopValue: {
    key: '保养停机值',
    lable: '停机寿命',
    value: '--'
  }
});

const tableData = [
  {
    partName: '传动带',
    currentValue: 200,
    warningValue: 500,
    stopValue: 600,
    jump: '跳转'
  },
  {
    partName: '中转罐',
    currentValue: 200,
    warningValue: 500,
    stopValue: 600,
    jump: '跳转'
  },
  {
    partName: '缓存罐',
    currentValue: 200,
    warningValue: 500,
    stopValue: 600,
    jump: '跳转'
  }
];

// 监听项目查询制浆机
const projectChange = async (value: string) => {
  if (value) {
    currentProjectId.value = value;
    // 项目改变清空选择部件
    currentPartId.value = '';
    // 获取全部部件
    const resp = await getPartsAsync(value);
    if (resp.message) return ElMessage.error(resp.message || '获取制浆机列表错误！');
    // 过滤出对应部件
    const result = resp.result || [];
    subcompoent.value = result;
    partsOption.value = result.filter((item) => {
      return !item.partOwnerId && anodeMixerRegex.test(item.partName);
    });
  }
};

// 监听制浆机查询对应值
const partChange = async (value: string) => {
  if (value) {
    currentPartId.value = value;
    subscribePartsAsync();
  }
};
</script>

<template>
  <main class="main-container">
    <div class="search-container">
      <div style="display: flex">
        <el-text class="mx-1">项目名称:</el-text>
        <div style="margin-left: 8px">
          <el-select
            class="project-name"
            @change="projectChange"
            style="width: 240px"
            v-model="currentProjectId"
          >
            <el-option
              v-for="item in projectOption"
              :key="item.id"
              :label="item.projectName"
              :value="item.id"
            />
          </el-select>
        </div>
      </div>
      <div style="display: flex; margin-left: 20px">
        <el-text class="mx-1">制浆机:</el-text>
        <div style="margin-left: 8px">
          <el-select
            class="part-name"
            @change="partChange"
            style="width: 240px"
            v-model="currentPartId"
          >
            <el-option
              v-for="item in partsOption"
              :key="item.id"
              :label="item.partName"
              :value="item.id"
            />
          </el-select>
        </div>
      </div>
    </div>
    <div class="content-container" @click="showTable = false">
      <div
        style="
          position: absolute;
          left: 50%;
          top: 10px;
          font-weight: bold;
          font-size: 24px;
          transform: translateX(-85%);
        "
      >
        阴极高速制浆机
      </div>
      <img
        src="@/assets/img/pulping-machine.png"
        style="
          position: absolute;
          left: 50%;
          top: 50%;
          width: 760px;
          transform: translate(-50%, -50%);
        "
        class="cursor-hover"
        @click.stop="showTable = true"
      />
      <svg style="position: absolute; left: 28%; top: 50%">
        <line x1="0" y1="0" x2="200" y2="100" stroke="green" stroke-width="5"></line>
      </svg>
      <svg style="position: absolute; left: 58%; top: 38%">
        <line x1="0" y1="105" x2="100" y2="0" stroke="green" stroke-width="5"></line>
      </svg>
      <svg style="position: absolute; left: 64%; top: 68%">
        <line x1="0" y1="0" x2="144" y2="0" stroke="green" stroke-width="10"></line>
      </svg>

      <el-card shadow="hover" style="position: absolute; left: 20%; top: 43%; width: 220px">
        <router-link to="/pulping-machine/BeltView" style="color: blue"
          >高速分散腔电机-传动带</router-link
        >
        <div style="margin-top: 10px">
          <span
            >{{ highSpeedMotor.currentSpeed.lable }}：{{
              highSpeedMotor.currentSpeed.value
            }}
            rpm</span
          >
        </div>
        <div style="margin-top: 10px">
          <span
            >{{ highSpeedMotor.currentValue.lable }}：{{
              highSpeedMotor.currentValue.value
            }}
            day</span
          >
        </div>
        <div style="margin-top: 10px">
          <span
            >{{ highSpeedMotor.warningValue.lable }}：{{
              highSpeedMotor.warningValue.value
            }}
            day</span
          >
        </div>
        <div style="margin-top: 10px">
          <span
            >{{ highSpeedMotor.stopValue.lable }}：{{ highSpeedMotor.stopValue.value }} day</span
          >
        </div>
      </el-card>
      <el-card shadow="hover" style="position: absolute; left: 72%; top: 50%; width: 180px">
        <router-link to="/pulping-machine/BeltView" style="color: blue">中转罐</router-link>
        <div style="margin-top: 10px">
          <span
            >{{ transferTank.currentSpeed.lable }}：{{ transferTank.currentSpeed.value }} rpm</span
          >
        </div>
        <div style="margin-top: 10px">
          <span
            >{{ transferTank.currentValue.lable }}：{{ transferTank.currentValue.value }} day</span
          >
        </div>
        <div style="margin-top: 10px">
          <span
            >{{ transferTank.warningValue.lable }}：{{ transferTank.warningValue.value }} day</span
          >
        </div>
        <div style="margin-top: 10px">
          <span>{{ transferTank.stopValue.lable }}：{{ transferTank.stopValue.value }} day</span>
        </div>
      </el-card>
      <el-card shadow="hover" style="position: absolute; left: 58%; top: 8%; width: 220px">
        <router-link to="/pulping-machine/MixingTankView" style="color: blue">循环罐A</router-link>
        <div style="margin-top: 10px">
          <span
            >{{ circulatingTankBeltA.pressure.lable }}：{{
              circulatingTankBeltA.pressure.value
            }}
            kpa</span
          >
        </div>
        <div style="margin-top: 10px">
          <span
            >{{ circulatingTankBeltA.mixingSpeed.lable }}：{{
              circulatingTankBeltA.mixingSpeed.value
            }}
            rpm</span
          >
        </div>
        <div style="margin-top: 10px">
          <span
            >{{ circulatingTankBeltA.distributeSpeed.lable }}：{{
              circulatingTankBeltA.distributeSpeed.value
            }}
            rpm</span
          >
        </div>
        <div style="margin-top: 10px">
          <span
            >{{ circulatingTankBeltA.currentValue.lable }}：{{
              circulatingTankBeltA.currentValue.value
            }}
            day</span
          >
        </div>
        <div style="margin-top: 10px">
          <span
            >{{ circulatingTankBeltA.warningValue.lable }}：{{
              circulatingTankBeltA.warningValue.value
            }}
            day</span
          >
        </div>
        <div style="margin-top: 10px">
          <span
            >{{ circulatingTankBeltA.stopValue.lable }}：{{
              circulatingTankBeltA.stopValue.value
            }}
            day</span
          >
        </div>
      </el-card>
      <el-card shadow="hover" style="position: absolute; left: 72%; top: 8%; width: 220px">
        <router-link to="/pulping-machine/MixingTankView" style="color: blue">循环罐B</router-link>
        <div style="margin-top: 10px">
          <span
            >{{ circulatingTankBeltB.pressure.lable }}：{{
              circulatingTankBeltB.pressure.value
            }}
            kpa</span
          >
        </div>
        <div style="margin-top: 10px">
          <span
            >{{ circulatingTankBeltB.mixingSpeed.lable }}：{{
              circulatingTankBeltB.mixingSpeed.value
            }}
            rpm</span
          >
        </div>
        <div style="margin-top: 10px">
          <span
            >{{ circulatingTankBeltB.distributeSpeed.lable }}：{{
              circulatingTankBeltB.distributeSpeed.value
            }}
            rpm</span
          >
        </div>
        <div style="margin-top: 10px">
          <span
            >{{ circulatingTankBeltB.currentValue.lable }}：{{
              circulatingTankBeltB.currentValue.value
            }}
            day</span
          >
        </div>
        <div style="margin-top: 10px">
          <span
            >{{ circulatingTankBeltB.warningValue.lable }}：{{
              circulatingTankBeltB.warningValue.value
            }}
            day</span
          >
        </div>
        <div style="margin-top: 10px">
          <span
            >{{ circulatingTankBeltB.stopValue.lable }}：{{
              circulatingTankBeltB.stopValue.value
            }}
            day</span
          >
        </div>
      </el-card>
      <el-card
        style="width: 270px; height: calc(100vh - 150px); position: absolute; left: 30px; top: 30px"
        shadow="hover"
      >
        <div style="display: flex">
          <div style="display: flex; align-items: center">
            <TrafficLight :color="highSpeedMotor.status"></TrafficLight>
            <span style="writing-mode: vertical-lr">高速分散腔电机</span>
          </div>
          <div style="display: flex; align-items: center; margin-left: 10px">
            <TrafficLight :color="circulatingTankBeltA.status"></TrafficLight>
            <span style="writing-mode: vertical-lr">循环罐A-电机</span>
          </div>
          <div style="display: flex; align-items: center; margin-left: 10px">
            <TrafficLight :color="circulatingTankBeltB.status"></TrafficLight>
            <span style="writing-mode: vertical-lr">循环罐B-电机</span>
          </div>
        </div>
        <div style="display: flex; margin-top: 20px">
          <div style="display: flex; align-items: center">
            <TrafficLight :color="transferTank.status"></TrafficLight>
            <span style="writing-mode: vertical-lr">中转罐</span>
          </div>
        </div>
      </el-card>
      <el-card class="content-right" shadow="hover">
        <div class="right-top">传送带：</div>
        <div>
          <div class="right-center">设备运行正常</div>
        </div>
        <div>
          <div class="right-foot">左真空滤芯：压强波动超过设定值 10 kpa 。</div>
        </div>
      </el-card>
      <el-card
        v-if="showTable"
        style="
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          width: 900px;
          height: 600px;
        "
      >
        <template #header><span>易损件列表</span></template>
        <el-table :data="tableData">
          <el-table-column prop="partName" label="部件名称" />
          <el-table-column prop="currentValue" label="当前寿命" />
          <el-table-column prop="warningValue" label="预警寿命" />
          <el-table-column prop="stopValue" label="停机寿命" />
          <el-table-column prop="jump" label="跳转地址">
            <RouterLink to="">查看</RouterLink>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </main>
</template>

<style scoped lang="scss">
.arrow-down {
  width: 0;
  height: 0;
  border-left: 50px solid transparent; /* 左边框透明 */
  border-right: 50px solid transparent; /* 右边框透明 */
  border-top: 100px solid black; /* 上边框为黑色，形成箭头 */
  /* 你可以根据需要调整这些值来改变箭头的大小和形状 */
}

.main-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fff;
  border-radius: 5px;
}

.content-container {
  padding: 0px 30px 20px 30px;
  border-radius: 5px;
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.search-container {
  padding: 15px 30px 0px 15px;
  border-radius: 5px;
  display: flex;
}

.cursor-hover:hover {
  cursor: pointer;
}
.project-name:focus,
.part-name:focus {
  outline: unset;
}
:deep(.el-select__wrapper:focus) {
  outline: unset;
}
.content-right {
    width: 270px;
    height: calc(100vh - 150px);
    position: absolute;
    left: 84.5%;
    top: 30px;
    .right-top {
      font-weight: bold;
    }
    .right-center {
      display: inline;
      color: green;
    }
    .right-foot {
      display: inline;
      color: red;
    }
  }
</style>
